package com.woniu.shop.service.impl;

import com.woniu.entity.Result;
import com.woniu.entity.ResultCode;
import com.woniu.shop.constant.RedisConstant;
import com.woniu.shop.entity.dto.ShopApplyDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.shop.mapper.ShopMapper;
import com.woniu.shop.pojo.Shop;
import com.woniu.shop.pojo.ShopApply;
import com.woniu.shop.utils.EmailUtil;
import com.woniu.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import com.woniu.shop.mapper.ShopApplyMapper;
import com.woniu.shop.pojo.ShopApply;
import com.woniu.shop.service.IShopApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.RegularUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.concurrent.ExecutionException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>
 * 门店申请表 服务实现类
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Service
@Slf4j
public class ShopApplyServiceImpl extends ServiceImpl<ShopApplyMapper, ShopApply> implements IShopApplyService {

    @Autowired(required = false)
    private ShopApplyMapper shopApplyMapper;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired(required = false)
    private ShopMapper shopMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public PageResult<ShopApply> checkRegistrationInfo(String shopName, Integer currentPage, Integer pageSize) {
        IPage<ShopApply> page = new Page(currentPage,pageSize);
        LambdaQueryWrapper<ShopApply> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(shopName),ShopApply::getShopName,shopName);
        IPage iPage = shopApplyMapper.selectPage(page, wrapper);
        return new PageResult<ShopApply>(iPage.getTotal(),iPage.getRecords());
    }


    @Override
    public Result<Object> apply(ShopApplyDTO shopApplyDTO) {

        // 1.对申请数据进行规则校验
        Field[] fields = shopApplyDTO.getClass().getDeclaredFields();
        for(Field field : fields){
            field.setAccessible(true);
            String methodName = "get" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1);
            try {
                Method method = shopApplyDTO.getClass().getMethod(methodName);
                Object value = method.invoke(shopApplyDTO);
                if(value == null){
                    return Result.error(ResultCode.ERROR.getCode(), "请检查申请信息是否填写完整");
                }
                // 校验身份证号
                if("getApplyIdNo".equals(methodName)){
                    if(!RegularUtil.regularIdNumber(value.toString())){
                        return Result.error(ResultCode.ERROR.getCode(), "身份证号格式不正确，请重新输入");
                    }
                }
                // 手机号校验
                if("getApplyPhone".equals(methodName)){
                    if(!RegularUtil.regularPhoneNumber(value.toString())){
                        return Result.error(ResultCode.ERROR.getCode(), "手机号码格式不正确，请重新输入");
                    }
                }
                // 邮箱校验
                if("getApplyEmail".equals(methodName)){
                    if(!RegularUtil.regularEmail(value.toString())){
                        return Result.error(ResultCode.ERROR.getCode(), "邮箱格式不正确，请重新输入");
                    }
                }
                // 性别校验
                if("getApplyGender".equals(methodName)){
                    if(!value.toString().matches("^(男|女){1}$" )){
                        return Result.error(ResultCode.ERROR.getCode(), "性别输入有误，请重新输入");
                    }
                    if("男".equals(value.toString()) && Integer.parseInt(shopApplyDTO.getApplyIdNo().substring(16,17)) % 2 == 0){
                        return Result.error(ResultCode.ERROR.getCode(), "性别校验不通过，请重新输入");
                    }
                    if("女".equals(value.toString()) && Integer.parseInt(shopApplyDTO.getApplyIdNo().substring(16,17)) % 2 != 0){
                        return Result.error(ResultCode.ERROR.getCode(), "性别校验不通过，请重新输入");
                    }
                }
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        // 2.组装实体数据
        ShopApply shopApply = new ShopApply();
        BeanUtils.copyProperties(shopApplyDTO, shopApply);
        IdWorker idWorker = new IdWorker();
        shopApply.setShopId(String.valueOf(idWorker.nextId()));
        shopApply.setApplyStatus("1"); // 待审核
        shopApply.setIsDeleted("0"); // 正常

        // 3.保存实体数据到数据库
        int row = shopApplyMapper.insert(shopApply);
        if(row == 0){
            return Result.error(ResultCode.INTERFACE_INNER_INVOKE_ERROR.getCode(), "原因是:数据保存失败");
        }

        // 4.将确认保存的图片记录到redis
        stringRedisTemplate.opsForSet().add(RedisConstant.ALIOSS_VALID_UPLOAD.name(),shopApplyDTO.getBusinessLicensePic());
        return Result.ok(shopApplyDTO.getBusinessLicensePic());
    }
    @Override
    public void registrationAndReview(String id) throws ExecutionException, InterruptedException {
        ShopApply shopApply = shopApplyMapper.selectById(id);
        String phone = shopApply.getApplyPhone();
        String email = shopApply.getApplyEmail();
        /*shopReviewDTO shopReviewDTO = new shopReviewDTO();
        BeanUtils.copyProperties(shopApply,shopReviewDTO);
        if(StringUtils.isEmpty(shopReviewDTO)) {
            shopApply.setApplyStatus("2");
            log.info("审核不通过，已驳回");
            // 发送消息通知门店
        }*/
/*
       boolean fieldsIsNotNull = ObjectUtil.checkObjFieldsIsNotNull(shopApply, Arrays.asList("shopName", "shopAddress", "shopDescription",
                "businessLicenseNum", "businessLicensePic", "applyName", "applyIdNo", "applyPhone", "applyEmail"));
*/

        if(shopApply.getShopName() == null || shopApply.getShopAddress() == null || shopApply.getApplyIdNo() == null || shopApply.getApplyName() == null ){
            shopApply.setApplyStatus("3");
            shopApply.setHandleResult("资料填写不完整");
            shopApplyMapper.updateById(shopApply);
            // 发送消息通知门店
            //SMSUtils.SendSms(phone,null);
            emailUtil.sendSimpleMail(email,"审核通知","审核不通过！请补充申请资料再次提交！");
        }
        else {
            shopApply.setApplyStatus("2");
            shopApply.setInitPassword("123456");
            shopApply.setHandleResult("审核已通过");
            shopApplyMapper.updateById(shopApply);
            Shop shop = new Shop();
            BeanUtils.copyProperties(shopApply, shop);
            IdWorker idWorker = new IdWorker();
            long nextId = idWorker.nextId();
            shop.setAccount(String.valueOf(nextId));
            shop.setLoginPwd("123456");
            shop.setId(shopApply.getShopId());
            // 如果申请两次，给出提醒
            shopMapper.insert(shop);
            // 发送消息通知门店
            //SMSUtils.SendSms(phone,null);
            emailUtil.sendSimpleMail(email, "审核通知", "审核通过！您的账号和初始登录密码分别为：" + shop.getAccount() + " , " + shop.getLoginPwd() + "，请前往门店管理平台进一步完善门店信息。");
        }
    }
}
